<template>
  <div>
    <el-upload
      action="/proxyApi/thirdparty/oss/upload"
      list-type="picture"
      :show-file-list="showFileList"
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      multiple
      :limit="maxCount"
      :on-exceed="handleExceed">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'multiUpload',
  props: {
    // 图片 URL 数组
    value: Array,
    // 最大上传图片数量
    maxCount: {
      type: Number,
      default: 30
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: null,
      // showFileList: true

    };
  },
  computed: {
    fileList: {
      get() {
        return this.value ? this.value.map(url => ({
          name: url.substr(url.lastIndexOf("/") + 1),
          url
        })) : [];
      },
      set(newValue) {
        // 更新父组件的 value 属性
        //this.$emit('input', newValue.map(item => item.url));
      }
    },
  
    // showFileList: {
    //   get: function () {
    //     return !!this.value;
    //   },
    //   set: function (newValue) {}
    // }

    showFileList() {
      return !!this.value; // 简单逻辑可以直接返回
    }
},
  watch: {
    value(newVal) {
      debugger;
      this.updateFileList();
    }
  },
  // created() {
  //   this.updateFileList(); // 初始化时更新 fileList
  // },
  methods: {
    updateFileList() {
      this.fileList = this.value ? this.value.map(url => ({ name: url.substr(url.lastIndexOf("/") + 1), url })) : [];
    },
    emitInput(fileList) {
      debugger;
      const urls = fileList.map(item => item.url);
      this.$emit('input', urls);
    },
    handleRemove(file, fileList) {
      debugger;
      this.emitInput(fileList);
    },
    handlePreview(file) {
      debugger;
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    handleUploadSuccess(response, file, fileList) {
      debugger;
      console.log("上传成功...", response);
      const newFile = { name: response.data.name, url: response.data.url };
      debugger
      fileList.push(newFile);
      this.emitInput(fileList);
    },
    handleExceed(files, fileList) {
      debugger;
      this.$message.warning(`最多只能上传 ${this.maxCount} 张图片`);
    }
  }

};
</script>

<style scoped>
.el-icon-plus {
  font-size: 24px;
  color: #8c939d;
}
</style>